import { createRenderer } from '../runtime-core'

function createElement(type) {
    return document.createElement(type);
}

function patchProp(el,key,prevVal,nextVal) {
    let isOn = (key:string) => /^on[A-Z]/.test(key)
    if(isOn(key)) {
        let event = key.slice(2).toLocaleLowerCase()
        el.addEventListener(event,nextVal)
    } else {
        if(nextVal === undefined || nextVal === null) {
            el.removeAttribute(key)
        } else {
            el.setAttribute(key,nextVal)
        }
    }
}

// 第三个参数为锚点，确定添加的未知
function insert(child,parent,anchor = null) {
    // parent.append(el)
    // 加入到anchor这个元素之前之前
    parent.insertBefore(child,anchor)
}

function remove(children) {
    const parent = children.parentNode
    if(parent) {
        parent.removeChild(children)
    }
}

function setElementText(el,text) {
    el.textContent = text
}

const renderer:any = createRenderer({
    createElement,
    patchProp,
    insert,
    remove,
    setElementText
})

export function createApp (...args) {
    return renderer.createApp(...args)
}

export * from "../runtime-core"